package com.example.mall.product.handler;

import com.example.mall.common.enums.StatusCodeEnum;
import com.example.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = {"com.example.mall.product.controller"})
public class MallExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) {
        log.error("未知异常！[" + e.getMessage() + "]", e);
        return R.error(StatusCodeEnum.PRODUCT_UNKNOWN).putErrorLog(e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        Map<String, String> errorFields = new LinkedHashMap<>();
        if (e.hasFieldErrors()) {
            e.getFieldErrors().forEach(f -> errorFields.put(f.getField(), "[实际值:" + f.getRejectedValue() + "]  " + f.getDefaultMessage()));
        }
        log.error("参数校验异常！[" + errorFields + "]", e);
        return R.error(StatusCodeEnum.PRODUCT_PARAM_VALID_ERROR).putErrorLog(errorFields);
    }
}
